//
//  YXPunchViewController.m
//  TASWorkHelper
//
//  Created by YUSIR on 2018/9/3.
//  Copyright © 2018年 并联科技. All rights reserved.
//

#import "YXPunchViewController.h"

@interface YXPunchViewController ()<BMKLocationServiceDelegate, BMKMapViewDelegate, BMKGeoCodeSearchDelegate>{
    BMKMapView *_mapView;
    BMKLocationService *_locService;
    BMKGeoCodeSearch *_geoCodeSearch;
    BMKPointAnnotation* _annotation;
}
//@property(nonatomic,retain)BMKMapView* mapView;//地图视图
//@property(strong,nonatomic)BMKLocationService* locService;

/** 用户当前位置*/
@property(nonatomic , strong) BMKUserLocation *userLocation;
/** 当前城市*/
@property (nonatomic, copy) NSString *city;

@property (strong, nonatomic) UIImage *usernameImg;
@property (strong, nonatomic) UILabel *usernameLabel;
@property (strong, nonatomic) UILabel *locationLabel;
@property (strong, nonatomic) UILabel * detailsLabel;
@property (strong, nonatomic) UILabel * addressLabel;
@property (strong, nonatomic) UILabel * timeLabel;
@property (strong, nonatomic) UIButton * punchBtn;
@property (strong, nonatomic) UIImageView* punchView;
@property (strong, nonatomic) YXTimer *timer;
@property (strong, nonatomic) MBProgressHUD * hud;
@end

@implementation YXPunchViewController

- (void)viewDidLoad {
    self.navigationItem.title = @"签到";
    [super viewDidLoad];
    [self initView];
    
    // 设置百度地图
    [self setupMapViewWithParam];
}


#pragma mark - Lazzy load
- (void)dateFunc
{
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setDateFormat:@"YYYY年MM月dd日"];
    NSString *timestamp = [formatter stringFromDate:[NSDate date]];
    [self.detailsLabel setText:timestamp];//时间在变化的语句
    YXLog(@"日期:%@--",timestamp);

}
- (void)timerFunc
{
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setDateFormat:@"HH:mm:ss"];
    NSString *times = [formatter stringFromDate:[NSDate date]];
    [self.timeLabel setText:times];//时间在变化的语句
    YXLog(@"now时间：%@",times);
}
//遵循代理写在viewwillappear中
- (void)viewWillAppear:(BOOL)animated {
    self.navigationController.navigationBar.barStyle = UIBarStyleBlack;
    [_mapView viewWillAppear];
    _mapView.delegate = self;
    _locService.delegate = self;
    _geoCodeSearch.delegate = self;
    
//    定时器创建开启
//    @WeakObj(self)
//    _timer = [[YXTimer alloc] init:^BOOL{
//        @StrongObj(self)
//        dispatch_async(dispatch_get_main_queue(), ^{
//            [self timerFunc];
//        });
//        return NO;
//    } repeat:YES repeatLoops:-1 delay:0 interval:1.0];
//    [_timer start];
    
    
    //if (self.hud) {
    self.hud = [MBProgressHUD showHUDAddedTo:self.navigationController.view animated:YES];
    //}
    self.hud.label.text = @"Loading";
    dispatch_async(dispatch_get_global_queue(QOS_CLASS_USER_INITIATED, 0), ^{
        if (self->_locService) {
            [self->_locService startUserLocationService];
        }
        sleep(1);
        dispatch_async(dispatch_get_main_queue(), ^{
            [self.hud hideAnimated:YES];
        });
    });
    //self.hud.mode = MBProgressHUDModeAnnularDeterminate;
    // self.hud.backgroundColor = [UIColor blackColor]; //设置遮罩背景色,默认为透明
    
    
}

- (void)viewWillDisappear:(BOOL)animated {
    [_mapView viewWillDisappear];
    _mapView.delegate = nil;
    _locService.delegate = nil;
    _geoCodeSearch.delegate = nil;
    
    [_timer stop];
}
-(void) initView {
    self.usernameLabel = [[UILabel alloc]init];
    self.usernameLabel.textColor = [UIColor darkGrayColor];
    self.usernameLabel.font = [UIFont boldSystemFontOfSize:15.f];
    self.usernameLabel.text = @"于桂成";
    
    
    
//    显示日期
    UIImageView * datatimeImg = [YXUICreators createImageView:[UIColor clearColor]
                                                        image:[UIImage imageNamed:@"datetime"]
                                                       radius:0.f
                                                         size:CGSizeMake(30, 30)];
    
    
    self.detailsLabel = [[UILabel alloc]init];
    self.detailsLabel.textColor = [UIColor grayColor];
    self.detailsLabel.font = [UIFont systemFontOfSize:14.f];
    self.detailsLabel.text = @"2018年01月01日";
//    显示公司
    UIImageView * organizationImg = [YXUICreators createImageView:[UIColor clearColor]
                                                        image:[UIImage imageNamed:@"organization"]
                                                       radius:0.f
                                                         size:CGSizeMake(30, 30)];
    self.locationLabel = [[UILabel alloc]init];
    self.locationLabel.textColor = [UIColor grayColor];
    self.locationLabel.font = [UIFont boldSystemFontOfSize:14.f];
    self.locationLabel.text = @"并联科技有限公司";
    
    UIImageView * firstSplitLine = [YXUICreators createImageView:[UIColor lightGrayColor]
                                                            image:nil
                                                           radius:0.f
                                                             size:CGSizeMake(SCREEN_WIDTH, 1)];
    
//    address
    UIImageView * addressImg = [YXUICreators createImageView:[UIColor clearColor]
                                                            image:[UIImage imageNamed:@"address"]
                                                           radius:0.f
                                                             size:CGSizeMake(20, 20)];
    self.addressLabel = [YXUICreators createLabelBgColor:[UIColor clearColor] textColor:[UIColor grayColor] fontSize:13.f textAlignment:NSTextAlignmentLeft];
    self.punchView = [YXUICreators createImageView:YXGlobalColor image:nil radius:punchViewWidth*(SCREEN_HEIGHT/SCREEN_HEIGHT_IPHONE6P)/2 size:CGSizeZero];
    self.punchBtn = [YXUICreators createButton:nil
                                        action:nil
                                         title:@"签到"
                                     titleSize:18.f
                         backgroundImageNormal:nil
                    backgroundImageHighlighted:nil
                                        radius:0];
    self.timeLabel = [YXUICreators createLabelBgColor:[UIColor clearColor] textColor:[UIColor whiteColor] fontSize:13.f textAlignment:NSTextAlignmentCenter];
    self.timeLabel.text = @"00:00:00";
    
    [self.view addSubview:self.usernameLabel];
    [self.view addSubview:self.locationLabel];
    
    [self.view addSubview:datatimeImg];
    [self.view addSubview:self.detailsLabel];
    [self.view addSubview:organizationImg];
    [self.view addSubview:self.detailsLabel];
    [self.view addSubview:firstSplitLine];
    [self.view addSubview:addressImg];
    
    [self.view addSubview:self.addressLabel];
    [self.view addSubview:self.punchView];
    [self.punchView addSubview:self.punchBtn];
    [self.punchView addSubview:self.timeLabel];
    
    @WeakObj(self)
    [self.usernameLabel makeConstraints:^(MASConstraintMaker *make) {
        @StrongObj(self)
        make.top.offset( NAVIGATION_BAR_HEIGHT + 5.f);
        make.left.equalTo(self.view.mas_left).offset(15.f);
        make.height.equalTo(30);
        make.width.equalTo(60.f);
    }];

    [datatimeImg makeConstraints:^(MASConstraintMaker *make) {
        @StrongObj(self)
        make.top.equalTo(self.usernameLabel.bottom).offset(5.f);
        make.left.equalTo(self.view.mas_left).offset(15.f);
        
    }];
    //日期显示位置
    [self.detailsLabel makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.equalTo(datatimeImg.centerY);
        make.left.equalTo(datatimeImg.mas_right).offset(5.f);
        make.height.equalTo(30);
        make.width.equalTo((SCREEN_WIDTH-100)/2);
    }];
//    公司组织显示
    [organizationImg makeConstraints:^(MASConstraintMaker *make) {
        @StrongObj(self)
        make.top.equalTo(self.usernameLabel.bottom).offset(5.f);
        make.left.equalTo(self.detailsLabel.mas_right).offset(5.f);
        
    }];
    [self.locationLabel makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.equalTo(organizationImg.centerY);
        make.left.equalTo(organizationImg.mas_right).offset(5.f);
        make.height.equalTo(30);
        make.width.equalTo((SCREEN_WIDTH-100)/2);
    }];
    
    [firstSplitLine makeConstraints:^(MASConstraintMaker *make) {
        @StrongObj(self)
        make.top.equalTo(self.detailsLabel.bottom).offset(10.f);
        make.left.equalTo(self.view.left);
        make.height.equalTo(1);
        make.width.equalTo(SCREEN_WIDTH);
    }];
    
    //地址
    [addressImg makeConstraints:^(MASConstraintMaker *make) {
        @StrongObj(self)
        make.top.equalTo(firstSplitLine.bottom).offset(15.f);
        make.left.equalTo(self.view.mas_left).offset(15.f);
    }];
    [self.addressLabel makeConstraints:^(MASConstraintMaker *make) {
        @StrongObj(self)
         make.centerY.equalTo(addressImg.centerY);
        make.left.equalTo(addressImg.mas_right).offset(5.f);
        make.height.equalTo(25);
        make.right.equalTo(self.view.mas_right).offset(8.f);
    }];
    [self.punchView makeConstraints:^(MASConstraintMaker *make) {
        @StrongObj(self)
        make.width.equalTo(punchViewWidth * (SCREEN_HEIGHT/SCREEN_HEIGHT_IPHONE6P));
        make.height.equalTo(punchViewWidth* (SCREEN_HEIGHT/SCREEN_HEIGHT_IPHONE6P));
        make.centerX.equalTo(self.view.mas_centerX);
        make.bottom.equalTo(self.view.mas_bottom).offset(-TABBAR_HEIGHT_IPHONE - 30 * (SCREEN_HEIGHT/SCREEN_HEIGHT_IPHONE6P));
    }];
    
    [self.punchBtn makeConstraints:^(MASConstraintMaker *make) {
        @StrongObj(self)
        make.width.equalTo(60);
        make.height.equalTo(30*(SCREEN_HEIGHT/SCREEN_HEIGHT_IPHONE6P));
        make.centerX.equalTo(self.view.mas_centerX);
        make.top.equalTo(self.punchView.mas_top).offset(30);
    }];
    [self.timeLabel makeConstraints:^(MASConstraintMaker *make) {
        @StrongObj(self)
        make.width.equalTo(self.punchBtn.mas_width);
        make.height.equalTo(15.f);
        make.centerX.equalTo(self.view.mas_centerX);
        make.top.equalTo(self.punchBtn.mas_bottom);
    }];
    
}
#pragma mark - 设置百度地图
-(void)setupMapViewWithParam {
    self.userLocation = [[BMKUserLocation alloc] init];
    _geoCodeSearch = [[BMKGeoCodeSearch alloc] init];
    _locService = [[BMKLocationService alloc] init];
    _locService.distanceFilter = 200;//设定定位的最小更新距离，这里设置 200m 定位一次，频繁定位会增加耗电量
    _locService.desiredAccuracy = kCLLocationAccuracyBest;//设定定位精度
    //开启定位服务
    [_locService startUserLocationService];
    //初始化BMKMapView
    _mapView = [[BMKMapView alloc] initWithFrame:CGRectMake(0, NAVIGATION_BAR_HEIGHT + 120, SCREEN_WIDTH, 200*(SCREEN_HEIGHT/SCREEN_HEIGHT_IPHONE6P))];
    
    _mapView.buildingsEnabled = NO;//设定地图是否现显示3D楼块效果
    //_mapView.overlookEnabled = YES; //设定地图View能否支持俯仰角
    _mapView.showMapScaleBar = YES; // 设定是否显式比例尺
    //  _mapView.overlooking = -45;     // 地图俯视角度，在手机上当前可使用的范围为－45～0度
    
    _mapView.zoomLevel = 18;//设置放大级别
    [self.view addSubview:_mapView];
    _mapView.userTrackingMode = BMKUserTrackingModeHeading;//设置定位的状态
    _mapView.showsUserLocation = YES;//显示定位图层
    BMKLocationViewDisplayParam *userlocationStyle = [[BMKLocationViewDisplayParam alloc] init];
    userlocationStyle.isRotateAngleValid = YES;
    userlocationStyle.isAccuracyCircleShow = YES;//显示精度圈
    [_mapView updateLocationViewWithParam:userlocationStyle];
}

#pragma mark - BMKLocationServiceDelegate 用户位置更新后，会调用此函数
- (void)didUpdateBMKUserLocation:(BMKUserLocation *)userLocation {
    //[self.hud showAnimated:YES];
    YXLog(@"userLocation.location:%@",userLocation.location);
    YXLog(@"定位的经度：%f,定位的维度：%f",userLocation.location.coordinate.longitude,userLocation.location.coordinate.latitude);
    [_mapView updateLocationData:userLocation];// 动态更新我的位置数据
    self.userLocation = userLocation;
    [_mapView setCenterCoordinate:userLocation.location.coordinate];// 当前地图的中心点
    //标注
    if (!_annotation) {
        _annotation = [[BMKPointAnnotation alloc]init];
        _annotation.coordinate = userLocation.location.coordinate;
        [_mapView addAnnotation:_annotation];
    }
    
    /// geo检索信息类,获取当前城市数据
    BMKReverseGeoCodeOption *reverseGeoCodeOption = [[BMKReverseGeoCodeOption alloc] init];
    reverseGeoCodeOption.reverseGeoPoint = userLocation.location.coordinate;
    [_geoCodeSearch reverseGeoCode:reverseGeoCodeOption];
    //[self.hud hideAnimated:YES];
    
}

#pragma mark 根据坐标返回反地理编码搜索结果
-(void)onGetReverseGeoCodeResult:(BMKGeoCodeSearch *)searcher result:(BMKReverseGeoCodeResult *)result errorCode:(BMKSearchErrorCode)error {
    BMKAddressComponent *addressComponent = result.addressDetail;
    YXLog(@"addressComponent:%@",addressComponent.city);
    YXLog(@"result.address:%@",result.address);
    YXLog(@"result.poiList:%@",result.poiList);
    self.city = addressComponent.city;
    NSString *title = [NSString stringWithFormat:@"%@%@%@%@", addressComponent.city, addressComponent.district, addressComponent.streetName, addressComponent.streetNumber];
    YXLog(@"%s -- %@", __func__, title);
    self.addressLabel.text = [NSString stringWithFormat:@"%@",title];
    
}
- (BMKAnnotationView *)mapView:(BMKMapView *)mapView viewForAnnotation:(id <BMKAnnotation>)annotation
{
    if ([annotation isKindOfClass:[BMKPointAnnotation class]]) {
        static NSString *pointReuseIndentifier = @"pointReuseIndentifier";
        BMKPinAnnotationView*annotationView = (BMKPinAnnotationView *)[mapView dequeueReusableAnnotationViewWithIdentifier:pointReuseIndentifier];
        if (annotationView == nil) {
            annotationView = [[BMKPinAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:pointReuseIndentifier];
        }
        annotationView.pinColor = BMKPinAnnotationColorPurple;
        annotationView.canShowCallout= YES;      //设置气泡可以弹出，默认为NO
        annotationView.animatesDrop=YES;         //设置标注动画显示，默认为NO
        annotationView.draggable = YES;          //设置标注可以拖动，默认为NO
        return annotationView;
    }
    return nil;
}
@end

